import * as Utils from "@/MUI/utils/Function";
const files = require.context(".", true, /\.js/);
const store = Utils.exportFileAsObject(files);

import Vue from "vue";
import Store from "@/store/index";
import Router from "@/router/index";

import { getAuth } from "@/request/common";
import defaultMenu from "@/config/menu";
import $config from "@/config";

const state = {
  routerLoading: true,
  data: [],
  arr: [],
  Home: {
    path: "/home",
    componentPath: "/main/home",
    meta: {
      title: "首页",
      type: 1,
      affix: true, //固定
      show: true,
    },
  },
  Source: {
    path: "/source",
    componentPath: "/main/source",
    meta: {
      title: "情报源接入",
      type: 1,
      affix: true, //固定
      show: true,
    },
    children: [],
  },
  Demo: {
    path: "/demo",
    meta: {
      title: "Demo",
      type: 0,
      show: true,
      subtitle: "",
    },
    children: [
      {
        path: "/demo/table",
        componentPath: "/main/demo/Table",
        meta: {
          title: "Demo-Table",
          type: 1,
          show: true,
          subtitle: "",
        },
      },
      {
        path: "/demo/form",
        componentPath: "/main/demo/Form",
        meta: {
          title: "Demo-Form",
          type: 1,
          show: true,
          subtitle: "",
        },
      },
      {
        path: "/demo/component",
        componentPath: "/main/demo/Component",
        meta: {
          title: "Demo-Component",
          type: 1,
          show: true,
          subtitle: "",
        },
      },
      {
        path: "/demo/method",
        componentPath: "/main/demo/Method",
        meta: {
          title: "Demo-Method",
          type: 1,
          show: true,
          subtitle: "",
        },
      },
      {
        path: "/demo/chart",
        componentPath: "/main/demo/Chart",
        meta: {
          title: "Demo-Chart",
          type: 1,
          show: true,
          subtitle: "",
        },
      },
      {
        path: "/demo/visualizationPanel",
        componentPath: "/main/demo/VisualizationPanel",
        meta: {
          title: "Demo-VisualizationPanel",
          type: 1,
          show: true,
          subtitle: "",
        },
      },
    ],
  },
  Error: {
    path: "/error",
    componentPath: "/main/error",
    meta: {
      title: "错误",
      type: 1,
      show: false,
      subtitle: "",
    },
  },
};

const getters = {
  hasAuth: (state) => (data) => {
    let result = false;
    let authArr = state.arr;
    var value = data;
    var hasPermission = authArr.some((e) => {
      return value.some((el) => {
        return e.meta.code === el;
      });
    });
    var passPermission = value.some((e) => {
      return e === "*";
    });

    if (passPermission) {
      result = true;
    } else if (hasPermission) {
      result = true;
    }
    if ($config.env === "development") {
      return true;
    }
    return result;
  },
};

const mutations = {};

const actions = {
  getAuth: ({ state }, code) => {
    return new Promise((resolve, reject) => {
      // getAuth({})
      //   .then((res) => {
      //     resolve(res.data.data);
      //   })
      //   .catch((err) => {
      //     reject();
      //   });
    });
  },
  authInit: ({ state }, data) => {
    let convertAuthData = (resData) => {
      let result = [];
      let objectR = (item) => {
        let obj;
        if (item) {
          if (item.menuType === "0") {
            obj = {
              path: item.path,
              meta: {
                type: Number(item.menuType),
                title: item.menuName,
                code: item.perms,
                show: item.visible === "1",
                icon: item.iconName,
                subtitle: "",
              },
            };
          } else if (item.menuType === "1") {
            obj = {
              path: item.path,
              componentPath: item.componentpath,
              meta: {
                type: Number(item.menuType),
                title: item.menuName,
                code: item.perms,
                show: item.visible === "1",
                keepAlive: item.isCache === "1",
                icon: item.iconName,
                subtitle: "",
              },
            };
          } else if (item.menuType === "2") {
            obj = {
              meta: {
                type: Number(item.menuType),
                title: item.menuName,
                code: item.perms,
                operationType: item.opeType,
                icon: item.iconName,
                subtitle: "",
              },
            };
          }
          if (item.child && item.child.length) {
            obj.children = item.child.map((e) => {
              return objectR(e);
            });
          }
        }
        if (!obj.meta.code) {
          obj.meta.code = "*";
        }
        if (obj.meta.code === "home") {
          obj.meta.affix = true; //固定
        }
        return obj;
      };
      if (resData && resData.length) {
        result = resData.map((e) => {
          return objectR(e);
        });
      }
      return result;
    };

    let arrInit = (data) => {
      let arr = [];
      let dataR = (item) => {
        arr.push(item);
        if (item.children && item.children.length) {
          item.children.forEach((e) => {
            dataR(e);
          });
        }
      };
      data.forEach((e) => {
        dataR(e);
      });
      state.arr = arr;
      console.log("arr", arr);
    };

    let routeData = [];
    if ($config.env === "development") {
      routeData = defaultMenu.data;
      // routeData.unshift(state.Source);
      // routeData.unshift(state.Home);
      // routeData.push(state.Demo); //打包注释
    } else if ($config.env === "production") {
      routeData = defaultMenu.data;
      // routeData.unshift(state.Source);
      // routeData.unshift(state.Home);
      // routeData.push(state.Demo); //打包注释
    } else {
      var hasHome = routeData.some(
        (e) => e && e.meta && ["home"].includes(e.meta.code)
      );
      if (!hasHome) {
        // routeData.unshift(state.Source);
        routeData.unshift(state.Home);
      }
    }

    routeData.push(state.Error);

    console.log("routeData", routeData);
    arrInit(routeData);
    Store.dispatch("createRouter", routeData);
    Store.commit("MMenuInit", routeData);
    Store.dispatch("getAuth")
      .then((res) => {
        let routeData = JSON.parse(JSON.stringify(convertAuthData(res)));
        if ($config.env === "development") {
          routeData = defaultMenu.data;
          routeData.unshift(state.Home);
          // routeData.unshift(state.Source);
          routeData.push(state.Demo); //打包注释
        } else {
          var hasHome = routeData.some(
            (e) => e && e.meta && ["home"].includes(e.meta.code)
          );
          if (!hasHome) {
            routeData.unshift(state.Home);
            routeData.unshift(state.Source);
          }
        }

        routeData.push(state.Error);

        console.log("routeData", routeData);
        arrInit(routeData);
        Store.dispatch("createRouter", routeData);
        Store.commit("MMenuInit", routeData);
      })
      .catch((err) => {
        let routeData = [state.Home];
        if ($config.env === "development") {
          routeData.push(state.Demo);
        }
        routeData.push(state.Error);

        Store.dispatch("createRouter", routeData);
        Store.commit("MMenuInit", routeData);
      });
  },
  createRouter: ({ state }, data) => {
    var authArr = [];
    function objectR(obj) {
      if (obj.meta.type === 0 || obj.meta.type === 1) {
        if (!obj.name) {
          var name = "";
          var nameArr = obj.componentPath
            ? obj.componentPath.split("/")
            : obj.path.split("/");
          nameArr.forEach((e) => {
            if (e !== "main") {
              name += e.charAt(0).toUpperCase(e) + e.slice(1);
            }
          });
          obj.name = name;
        }

        if (obj.componentPath) {
          obj.component = () =>
            import(
              /* webpackChunkName: "main" */ "@/views" + obj.componentPath
            );
        } else {
          obj.component = Vue.component("m-empty", {
            render() {
              return <router-view></router-view>;
            },
          });
        }
        // obj.component = (resolve) => require(['@/views/' + obj.componentPath ], resolve)
        if (obj.children && obj.children.length) {
          obj.children = obj.children.map((e) => {
            return objectR(e);
          });
        }
        let routerObj = {
          ...obj,
          children: [],
        };

        authArr.push(routerObj);
      } else {
        // authArr.push(obj)
      }
      return obj;
    }

    data = data.map((e) => {
      return objectR(e);
    });
    console.log(data);
    var mainRouter = {
      path: "/",
      component: () =>
        import(/* webpackChunkName: "main" */ "@/views/main/index"),
      redirect: { name: "Home" },
      children: authArr,
    };

    console.log("mainRouter", mainRouter);
    Router.addRoute(mainRouter);
    state.routerLoading = false;
  },
};

export default {
  state,
  getters,
  mutations,
  actions,
  modules: {
    ...store,
  },
};
